package cqrtplm.aop;

import cn.hutool.core.util.ObjectUtil;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.mapper.RTClassificationMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;

@Aspect
@Component
@Slf4j
public class RTProductClassifyAOP {

    @Resource
    private RTClassificationMapper rtClassificationMapper;

    @AfterReturning("execution(* com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartService.updatePart(*))")
    public void updateProductClassify() {
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        String classIdStr = getRequestAttribute(request, "classId");
        String masteredoidStr = getRequestAttribute(request, "masteredoid");
        if (ObjectUtil.isEmpty(classIdStr) || ObjectUtil.isEmpty(masteredoidStr)) {
            return;
        }
        try {
            BigInteger classId = BigInteger.valueOf(Long.parseLong(classIdStr));
            BigInteger masteredoid = BigInteger.valueOf(Long.parseLong(masteredoidStr));
            rtClassificationMapper.updateProductClassify(classId, masteredoid);
        } catch (NumberFormatException e) {
            throw  RTErrorCodeEnum.CATEGORY_MODIFICATION_FAILED.getException("修改分类失败");
        }
    }

    private String getRequestAttribute(HttpServletRequest request, String name) {
        Object value = request.getAttribute(name);
        return value != null ? value.toString() : null;
    }
}